'use strict'

const { CryptUtil } = require('../Util')
const { ERR } = require('../../../constants')
const { Admin } = require('../Models')

class AdminAuth {
  async handle({ request }, next) {
    const payload = CryptUtil.jwtDecode(request.header('Authorization') || request.input('token'))
    console.log('=>', payload)
    if (!payload) {
      throw ERR.AUTH_FAILED
    } else {
      if (!payload.adminID) {
        throw ERR.AUTH_FAILED
      }
      request.adminID = payload.adminID
      let adminUser = await Admin.query().where('id', request.adminID).first()
      adminUser = adminUser.toJSON()
      delete adminUser.password
      // console.log(adminUser,'adminUser')
      request.adminUser = adminUser
    }
    await next()
  }
}

module.exports = AdminAuth
